package com.hunttown.common.sharding.client.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

public class BeanPropertyAccessUtil {
    public BeanPropertyAccessUtil() {
    }

    public static void setPropertyValue(String propertyName, Object propertyValue, Object object) throws InvocationTargetException, IllegalAccessException {
        if (!StringUtils.isBlank(propertyName) && object != null) {
            PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(object.getClass(), propertyName);
            if (descriptor != null && descriptor.getWriteMethod() != null) {
                descriptor.getWriteMethod().invoke(object, propertyValue);
            }

        } else {
            throw new IllegalArgumentException("'propertyName' cann't be null or empty,'object' cann't be null!");
        }
    }

    public static Object getPropertyValue(String propertyName, Object object) throws InvocationTargetException, IllegalAccessException {
        if (!StringUtils.isBlank(propertyName) && object != null) {
            PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(object.getClass(), propertyName);
            return descriptor != null && descriptor.getReadMethod() != null ? descriptor.getReadMethod().invoke(object) : null;
        } else {
            throw new IllegalArgumentException("'propertyName' cann't be null or empty,'object' cann't be null!");
        }
    }
}